﻿using CDH_Shop.Models.Database;
using CDH_Shop.Models.Order;
using CDH_Shop.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Transactions;

namespace CDH_Shop.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly CDH_ShopContext _db;
        private readonly ICarService _carService;
        private readonly IGoodService _goodService;
        /// <summary>
        /// 订单构造函数
        /// </summary>
        /// <param name="db"></param>
        public OrderController(CDH_ShopContext db, ICarService carService, IGoodService goodService)
        {
            _db = db;
            _carService = carService;
            _goodService = goodService;
        }

        //结算接口（把购物车商品生成订单和订单明细，进行结算，扣除商品库存，订单进入待发货状态【支付功能略过】）（需授权） 输入：无 输出：结算消息
        /// <summary>
        /// 结算接口
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public string AddOrder()
        {
            //先获取用户的购物车数据   
            var userId = Convert.ToInt32(Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);

            //开启数据库的事务
            using (var scope = new TransactionScope())
            {
                try
                {
                    var cars = _db.Cars.Where(x => x.Uid == userId).ToList();
                    if (!cars.Any())
                        return "购物车无数据";
                    //根据购物车获取库存消息
                    var stockMsg = _goodService.GetStock(cars);
                    if (stockMsg != "")
                        return stockMsg + "库存不足";

                    //根据购物车数据生成订单 和 订单明细
                    var order = new Order
                    {
                        CreteTime = DateTime.Now,
                        OrderCode = DateTime.Now.Ticks.ToString(),
                        ShipCom = string.Empty,
                        ShipNum = string.Empty,
                        //0待付款 1待发货 2待收货 3待评价
                        OrderState = 1,
                        UserId = userId,
                        TotalPrice = cars.Sum(x => x.Count * x.Price)
                    };
                    _db.Orders.Add(order);
                    //必须先提交保存更改后 才能拿到OrderId
                    _db.SaveChanges();
                    //遍历购物车数据
                    var orderDetailList = new List<OrderDetail>();
                    foreach (var item in cars)
                    {
                        var orderDetail = new OrderDetail
                        {
                            GoodId = item.GoodId,
                            GoodCover = item.GoodCover,
                            Count = item.Count,
                            GoodName = item.GoodName,
                            GoodPrice = item.Price,
                            TotalPrice = item.Price * item.Count,
                            OrderId = order.OrderId,
                        };
                        orderDetailList.Add(orderDetail);
                        _db.OrderDetails.Add(orderDetail);
                    }

                    //订单在这里提交成功了 库存扣除失败 
                    //实际库存少了 系统库存多了

                    //清空用户购物车
                    _carService.ClearCar(userId);
                    //扣除商品库存 遇到网络波动 数据库连接超时 失败
                    _goodService.UpdateStock(orderDetailList);
                    var row = _db.SaveChanges();
                    //当上面的SaveChange失败 不会执行下面的事务提交Complete
                    scope.Complete();
                    if (row > 0)
                        return "结算完成";
                    return "结算失败";
                    // 如果所有的操作都执行成功，则Complete()会被调用来提交事务
                    // 如果发生异常，则不会调用它并回滚事务
                }
                catch (Exception ex)
                {
                    // 处理异常 
                    return "出现异常请重新尝试";
                }
            }

        }

        //用户订单列表（需授权） 输入：订单状态 输出：用户订单数据查看订单商品，订单价格，订单状态
        /// <summary>
        /// 用户订单列表orderType //-1全部 0待付款 1待发货 2待收货 3待评价
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public List<UserOrder> GetUserOrder(int orderState)
        {
            var userId = Convert.ToInt32(Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
            var orderDb = _db.Orders.Where(x => x.UserId == userId).AsQueryable();
            //如果>=0添加条件
            if (orderState >= 0)
                orderDb.Where(x => x.OrderState == orderState);

            var orderList = orderDb
                .Select(x => new UserOrder
                {
                    CreateTime = x.CreteTime,
                    OrderCode = x.OrderCode,
                    OrderId = x.OrderId,
                    TotalPcice = x.TotalPrice,
                    OrderState = x.OrderState,
                }).ToList();

            foreach (var item in orderList)
            {
                //查询订单明细
                item.OrderDetails = _db.OrderDetails.Where(x => x.OrderId == item.OrderId).ToList();
                item.Count = item.OrderDetails.Sum(x => x.Count);
            }
            return orderList;
        }
        /// <summary>
        /// 后台管理员查询订单数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<AdminOrder> GetAdminOrder(GetAdminOrderReqest request)
        {
            var orderDb = _db.Orders.AsQueryable();
            if (!string.IsNullOrEmpty(request.OrderCode))
                orderDb = orderDb.Where(x => x.OrderCode == request.OrderCode);

            var list = orderDb
                  .Join(_db.Users, x => x.UserId, y => y.UserId, (x, y) => new AdminOrder
                  {
                      Mobile = y.Mobile,
                      OrderCode = x.OrderCode,
                      OrderId = x.OrderId,
                      TotalPrice = x.TotalPrice,
                  })
                  .OrderByDescending(x => x.OrderId)
                  .Skip((request.PageIndex - 1) * request.PageSize)
                  .Take(request.PageSize)
                  .ToList();
            foreach (var item in list)
            {
                //查询订单明细
                item.OrderDetails = _db.OrderDetails.Where(x => x.OrderId == item.OrderId).ToList();
            }
            return list;
        }
        /// <summary>
        /// 后台发货功能（点击发货按钮输入快递公司和快递单号，对订单状态进行更新，更新为已发货状态） 输入：订单Id,快递公司，快递单号 输出：发货消息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string OrderSend(OrderSendRequest request)
        {
            var order = _db.Orders.FirstOrDefault(x => x.OrderId == request.OrderId);
            if (order == null)
                return "订单不存在";

            order.OrderState = 2;
            order.ShipCom = request.ShipCom;
            order.ShipNum = request.ShipNum;
            _db.Orders.Update(order);
            var row = _db.SaveChanges();
            if (row > 0)
                return "发货成功";
            return "发货失败";
        }


        //银行转账系统

        //A用户 转账100给 B用户 功能

        //A的账号余额-100
        //B的账号余额+100
        //同时完成的 事务


        //账号密码加密优化

        //MD5算法
        //用于验证完整性
        //单向转换
        //字符串 转换成 32位字符串
        //密码、一本小说、一个程序
    }
}
